//
//  TrafficPeccancyQueryViewController.m
//  TrafficPeccancyQuery
//
//  Created by Vitas on 2018/7/5.
//  Copyright © 2018年 Bylongma. All rights reserved.
//

#import "MNDTrafficPeccancyQueryViewController.h"
#import "SYAlertViewController.h"
#import "CarmeraViewController.h"
#import "CitiesViewController.h"
#import "ShortCityNameModel.h"
#import "CityShortNameViewController.h"
#import "TPQTemplateViewController.h"
#import "ALYVinBackModel.h"
#import "MNDTPQResultViewController.h"
#import "MNDTPQResultModel.h"

@interface MNDTrafficPeccancyQueryViewController ()

@property (weak, nonatomic) IBOutlet UIButton *cityShortNameButton;
@property (weak, nonatomic) IBOutlet UITextField *carLicenseNumTextField;
@property (weak, nonatomic) IBOutlet UITextField *engineTextField;
@property (weak, nonatomic) IBOutlet UITextField *VINTextField;

@property (weak, nonatomic) IBOutlet UIView *engineContainerView;
@property (weak, nonatomic) IBOutlet UIView *VINContainerView;

@property(nonatomic, strong) ShortCityNameModel *shortCityModel;
@property(nonatomic, strong) ALYVinBackModel *vinModel;

//选择的车牌城市
@property(nonatomic, strong) CityModel *selectCityModel;

@end

@implementation MNDTrafficPeccancyQueryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取车牌城市
    [self loadCarNumCityData];
    
    [self setupUI];
    
    // Do any additional setup after loading the view.
}

- (void)setupUI {
    kdeclare_weakself;
    [[self.carLicenseNumTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        if (weakSelf.carLicenseNumTextField.text.length > 8) {
            weakSelf.carLicenseNumTextField.text = [x substringToIndex:8];
        }
    }];
}

//获取车牌城市
- (void)loadCarNumCityData {
    kdeclare_weakself;
    [NetworkProgressHUD showHud];
    [APIManager sendRequestWithURL:API_PROVINCE_VIOLATIONS parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        [NetworkProgressHUD hideHud];
        if (responseModel.status == ResponseSuccess) {
            NSLog(@"message: %@", responseModel.data);
            weakSelf.shortCityModel = [ShortCityNameModel mj_objectWithKeyValues:responseModel.data];
            if (weakSelf.shortCityModel.proCity.count > 0) {
                ProCityModel *provinceModel = self.shortCityModel.proCity[0];
                [weakSelf.cityShortNameButton setTitle:provinceModel.abbr forState:UIControlStateNormal];
                CityModel *cityModel = provinceModel.citys[0];
                weakSelf.selectCityModel = cityModel;
                weakSelf.carLicenseNumTextField.text = cityModel.abbr;
                weakSelf.engineTextField.placeholder = cityModel.engineTxt;
                weakSelf.VINTextField.placeholder = cityModel.carframeTxt;
            }
            
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}



#pragma mark - Action

//车牌号省份选择
- (IBAction)shortCityNameAction:(id)sender {

    kdeclare_weakself;
    NSArray *array = self.shortCityModel.proCity;
    if (array.count <= 0) {
        [self loadCarNumCityData];
        return;
    }
    
    [self.engineTextField resignFirstResponder];
    [self.carLicenseNumTextField resignFirstResponder];
    [self.VINTextField resignFirstResponder];
    [CityShortNameViewController showShortCityPicker:self cityNameArray: array selectedCityHandler:^(NSInteger index) {

        [weakSelf configContentsWithIndex:index];
    }];
}

#pragma mark - Action

- (IBAction)helperAction:(id)sender {
    TPQTemplateViewController *templateVC = [UIStoryboard viewControllerWithIdentifier:[TPQTemplateViewController description]];
    
    [KeyWindow addSubview:templateVC.view];
    [self addChildViewController:templateVC];
}

- (void)configContentsWithIndex:(NSInteger)index {
    ProCityModel *provinceModel = self.shortCityModel.proCity[index];
    [self.cityShortNameButton setTitle:provinceModel.abbr forState:UIControlStateNormal];
    CityModel *cityModel = provinceModel.citys[0];
    self.carLicenseNumTextField.text = cityModel.abbr;
    self.engineTextField.placeholder = cityModel.engineTxt;
    self.VINTextField.placeholder = cityModel.carframeTxt;
    self.selectCityModel = cityModel;
    kdeclare_weakself;
    [[self.engineTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
       
        if (weakSelf.engineTextField.text.length > cityModel.engine.integerValue) {
            weakSelf.engineTextField.text = [x substringToIndex:cityModel.engine.integerValue];
        }
        if (self.vinModel) {
            if (cityModel.engine.integerValue > 0) {
                 weakSelf.engineTextField.text = [self.vinModel.engine_num substringFromIndex:self.vinModel.engine_num.length - cityModel.engine.integerValue];
            }else {
                weakSelf.engineTextField.text = self.vinModel.engine_num;
            }
        }
    }];
    
    [[self.VINTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        
        if (weakSelf.VINTextField.text.length > cityModel.carframe.integerValue) {
            weakSelf.VINTextField.text = [x substringToIndex:cityModel.carframe.integerValue];
        }
        
        if (self.vinModel) {
            weakSelf.VINTextField.text = [self.vinModel.vin substringFromIndex:self.vinModel.vin.length - cityModel.carframe.integerValue];
        }
    }];
}

- (IBAction)takePhotoAction:(UIButton *)sender {
    kdeclare_weakself;
    SYAlertViewController *alert = [SYAlertViewController alertWithTitle:nil
                                                             cancelTitle:@"取消"
                                                       otherButtonTitles:@[@"拍照", @"相册"] cancelHandler:^{
                                                           
                                                       } otherButtonClickHandler:^(NSInteger clickIndex) {
                                                           if(clickIndex == 0) {
                                                               [weakSelf photoFromCamera];
                                                           }else {
                                                               [weakSelf photoFromAlbum];
                                                           }
                                                       }];
    
    alert.otherTitleColor = kColorOrange;
    
    [alert showInViewController:self];
}

//城市选择
- (IBAction)locationButtonAction:(id)sender {
    
//    kdeclare_weakself;
    CitiesViewController *citiesVC = [[CitiesViewController alloc] init];
    citiesVC.provinceOriginalArr = [self.shortCityModel.proCity copy];
    citiesVC.title = @"查询地区";
    citiesVC.citySelctedBlock = ^(CityModel *selctedCity) {

//        [weakSelf.locationButton setTitle:selctedCity.cityName forState:UIControlStateNormal];
    };

    [self.navigationController pushViewController:citiesVC animated:YES];
}

//相机获取图片
- (void)photoFromCamera {
    kdeclare_weakself;
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"CarmeraViewController" bundle:nil];
    CarmeraViewController *carmeraVC = [storyBoard instantiateViewControllerWithIdentifier:@"CarmeraViewController"];
    carmeraVC.saveImage = NO;
    carmeraVC.imageStr = @"drive_front";
    [self presentViewController:carmeraVC animated:YES completion:nil];
    void(^imageBlock)(UIImage *) = ^(UIImage *image) {
        
        [weakSelf getVinInfo:image];
        
    };
    carmeraVC.imageBlock = imageBlock;
}



//相册获取图片
- (void)photoFromAlbum {
    //首先需要判断资源是否可用
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //获得相机模式下支持的媒体类型
        //        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        pickerImage.delegate = self;
        //设置允许编辑
        pickerImage.allowsEditing = NO;
        
        [self presentViewController:pickerImage animated:YES completion:^{
        }];
    }
}


#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //    NSDictionary *param = @{};
    kdeclare_weakself;
    //获取裁剪后的图像
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        //开始获取行驶证信息
        [weakSelf getVinInfo:image];
    }];
}

#pragma mark - 取消操作时调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

//获取行驶证信息
- (void)getVinInfo:(UIImage *)vinImage {
    [NetworkProgressHUD showHud];
    
    
    kdeclare_weakself;
    [APIManager uploadWithUrl:API_SCAN_VIN parameters:[MNDSign signedParam] uploadImages:vinImage imageName:@"img" onProgress:^(NSProgress *progress) {
        
    } onSuccess:^(ResponseModel *response) {
        if (response.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            weakSelf.vinModel = [ALYVinBackModel mj_objectWithKeyValues:response.data];
            if (weakSelf.vinModel && weakSelf.vinModel.plate_num.length > 0) {
                [weakSelf configVinContent:weakSelf.vinModel];
                //               [weakSelf manualQueryAction:nil];
            } else {
                [NetworkProgressHUD showHudMsg:@"无法识别图片，请重试"];
            }
            
        }else {
            [NetworkProgressHUD showHudMsg:response.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    } onFinish:^(id responseObj, NSError *error) {
        
    }];
    
}

- (void)configVinContent:(ALYVinBackModel *)vinModel{
    [self.cityShortNameButton setTitle:[vinModel.plate_num substringToIndex:1] forState:UIControlStateNormal];
    self.carLicenseNumTextField.text = [vinModel.plate_num substringFromIndex:1];
    //匹配驾驶证城市发动机号，车架号输入位数要求
    if (self.shortCityModel) {
        for (ProCityModel *proModel in self.shortCityModel.proCity) {
            if ([proModel.abbr isEqualToString:[vinModel.plate_num substringToIndex:1]]) {
                for (CityModel *cityModel in proModel.citys) {
                    NSString *str = [vinModel.plate_num substringWithRange:NSMakeRange(1, 1)];
                    if ([cityModel.abbr isEqualToString:str]) {
                        self.selectCityModel = cityModel;
                        if (cityModel.engine.integerValue >= 6) {
                            self.engineTextField.text = [vinModel.engine_num substringFromIndex:vinModel.engine_num.length - cityModel.engine.integerValue];
                        }else {
                            self.engineTextField.text = vinModel.engine_num;
                        }
                        
                        self.engineTextField.placeholder = cityModel.engineTxt;
                        
                        self.VINTextField.text = [vinModel.vin substringFromIndex:vinModel.vin.length - cityModel.carframe.integerValue];
                        self.VINTextField.placeholder = cityModel.carframeTxt;
                        
                    }
                }
            }
        }
    }
    
}

- (IBAction)confirmAction:(UIButton *)sender {
    if (self.carLicenseNumTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入车牌号"];
        return;
    }
    if (self.engineTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入发动机号"];
        return;
    }
    if (self.VINTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入车架号"];
        return;
    }
    
    [NetworkProgressHUD showHud];
    kdeclare_weakself;
    NSDictionary *dict = @{
                           @"city":self.selectCityModel.cityCode,
                           @"city_name":self.selectCityModel.cityName,
                           @"carno":[NSString stringWithFormat:@"%@%@",self.cityShortNameButton.titleLabel.text,self.carLicenseNumTextField.text],
                           @"engineno":self.engineTextField.text,
                           @"carframe":self.VINTextField.text,
                           @"whole_carframe":self.vinModel ? self.vinModel.vin:self.VINTextField.text,
                           @"whole_engineno":self.vinModel ? self.vinModel.engine_num:self.engineTextField.text
                           };
    [APIManager sendRequestWithURL:API_QUERY_BREAK_RULES parameters:[MNDSign signedParamWithDict:dict] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        [NetworkProgressHUD hideHud];
        if (responseModel.status == ResponseSuccess) {
            MNDTPQResultModel *model = [MNDTPQResultModel mj_objectWithKeyValues:responseModel.data];
            MNDTPQResultViewController *resultVC = [UIStoryboard viewControllerWithIdentifier:@"MNDTPQResultViewController"];
            resultVC.resultModel = model;
            [weakSelf.navigationController pushViewController:resultVC animated:YES];
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
